﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace StudyUdp
{
    /// <summary>
    /// UdpCaseByUdpClient.xaml 的交互逻辑
    /// </summary>
    public partial class UdpCaseByUdpClient : Window
    {
        UdpClient client;

        public UdpCaseByUdpClient()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnOpen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region 用Socket实现(udp是不基于连接的，直接发送数据,即使对方不在线也可以发送，还可以自己给自己发)
                //client = new Socket(SocketType.Dgram, ProtocolType.Udp);
                //string ip = txtIP.Text;
                //int port = Convert.ToInt32(txtPort.Text);
                //client.Bind(new IPEndPoint(IPAddress.Parse(ip), port));

                //BtnOpen.Visibility = Visibility.Collapsed;
                //BtnClose.Visibility = Visibility.Visible;

                //AppendTxt("打开成功", Colors.Green);
                #endregion

                #region 用UdpClient实现
                string ip = txtIP.Text;
                int port = Convert.ToInt32(txtPort.Text);
                client = new UdpClient(new IPEndPoint(IPAddress.Parse(ip), port));

                BtnOpen.Visibility = Visibility.Collapsed;
                BtnClose.Visibility = Visibility.Visible;

                AppendTxt("打开成功", Colors.Green);
                #endregion

                #region 接收信息
                Task.Run(async () =>
                {
                    while (true)
                    {
                        _ = Dispatcher.Invoke(async () =>
                        {
                            if (client.Client != null && client.Available > 0)
                            {
                                UdpReceiveResult result = await client.ReceiveAsync();
                                if (result.Buffer.Length > 0)  // 有数据
                                {
                                    string recMsg = Encoding.UTF8.GetString(result.Buffer);
                                    AppendTxt($"来自{result.RemoteEndPoint}的信息:{recMsg}", Colors.Blue);
                                }
                            }

                        });

                        await Task.Delay(1000);
                    }
                });
                #endregion
            }
            catch (Exception ex)
            {
                BtnOpen.Visibility = Visibility.Visible;
                BtnClose.Visibility = Visibility.Collapsed;

                AppendTxt($"打开异常,{ex.Message}", Colors.Red);
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            if (client != null)
            {
                client.Close();
                BtnOpen.Visibility = Visibility.Visible;
                BtnClose.Visibility = Visibility.Collapsed;

                AppendTxt("已关闭", Colors.Red);
            }
        }

        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnSend_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (client != null)
                {
                    #region 发送
                    string sendMsg = txtSendContent.Text;
                    byte[] sendBytes = Encoding.UTF8.GetBytes(sendMsg);
                    await client.SendAsync(sendBytes, new IPEndPoint(IPAddress.Parse(txtRecIP.Text), int.Parse(txtRecPort.Text)));

                    AppendTxt($"发送信息:{sendMsg}", Colors.Black);
                    #endregion

                    #region 广播消息
                    //string sendMsg = txtSendContent.Text;
                    //byte[] sendBytes = Encoding.UTF8.GetBytes(sendMsg);
                    //client.EnableBroadcast = true; // 设置支持广播发送
                    ////await client.SendAsync(sendBytes, new IPEndPoint(IPAddress.Parse("192.168.2.255"), 9999));
                    //await client.SendAsync(sendBytes, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 9999));

                    //AppendTxt($"发送信息:{sendMsg}", Colors.Black);
                    #endregion



                }
            }
            catch (Exception ex)
            {
                AppendTxt($"发送信息异常:{ex.Message}", Colors.Red);
            }

        }


        FlowDocument doc = new FlowDocument();
        /// <summary>
        /// 追加文本
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="txtColor">文字颜色</param>
        private void AppendTxt(string txt, Color txtColor)
        {
            var p = new Paragraph(); // Paragraph 类似于 html 的 P 标签
            var r = new Run($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} {txt}"); // Run 是一个 Inline 的标签
            p.Inlines.Add(r);
            p.Foreground = new SolidColorBrush(txtColor);//设置字体颜色
            doc.Blocks.Add(p);
            txtShowContent.Document = doc;
            txtShowContent.ScrollToEnd();
        }


    }
}
